<template>
  <div style="display: flex; justify-content: center; margin-top: 10px">
    <el-form :model="dataForm" label-width="auto" style="width: 900px">
      <el-form-item label="国家代码类型">
        <div class="flex" style=" align-items: center;width: 100%">
          <el-select v-model="dataForm.countryType" style="margin-right: 15px" placeholder="请选择">
            <el-option label="Alpha-2" value="Alpha-2" />
            <el-option label="Alpha-3" value="Alpha-3" />
            <el-option label="自定义" value="Auto" />
          </el-select>

          <el-dropdown @command="handleClickDropdown">
            <span class="el-dropdown-link">
              下载国家列表
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item name="Alpha-2">Alpha-2</el-dropdown-item>
                <el-dropdown-item name="Alpha-3">Alpha-3</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-form-item>
      <el-form-item v-if="['Alpha-2', 'Alpha-3'].includes(dataForm.countryType)" label="大小写">
        <el-select v-model="dataForm.case" placeholder="请选择">
          <el-option label="大写" value="upper" />
          <el-option label="小写" value="lower" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="dataForm.countryType === 'Auto'" label="国家JSON">
        <el-upload
          ref="upload"
          class="upload-demo"
          action=""
          multiple
          :auto-upload="false"
          :limit="1"
          accept=".json"
          :on-exceed="handleExceed"
          :on-change="handleChange"
        >
          <el-button type="primary">上传国家JSON</el-button>
        </el-upload>
        <el-table :data="dataForm.countries" style="width: 100%" height="250" border>
          <el-table-column prop="key" label="key" fixed>
            <template #default="scope">
              <el-input v-model="scope.row.key" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column prop="code" label="code">
            <template #default="scope">
              <el-input v-model="scope.row.code" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="name">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100px">
            <template #default="scope">
              <el-button type="danger" text @click="handleDelete(scope.$index, dataForm.countries)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="产品列表">
        <el-table :data="dataForm.products" style="width: 100%" border>
          <el-table-column prop="key" label="应用" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.key" placeholder="请选择">
                <el-option
                  v-for="(item, index) in productSelectOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="value" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.value" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100px">
            <template #default="scope">
              <el-button type="danger" text @click="handleDelete(scope.$index, dataForm.products)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="small" :icon="Plus" style="width: 100%" @click="handleAddProduct">
          添加
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { genFileId } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import useCountries from "@/hooks/useCountries";
const { countriesList, countriesList3 } = useCountries();

const productSelectOptions = ref(["WA", "TG", "VIBER"]);

const dataForm = ref({
  case: "",
  countryType: "",
  countries: [],
  products: [
    {
      value: "",
      key: "WA",
    },
    {
      value: "",
      key: "TG",
    },
    {
      value: "",
      key: "VIBER",
    },
  ],
});

const upload = ref();
const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};

const handleDelete = (index, arr) => {
  arr.splice(index, 1);
};
// const handleAddCountry = () => {
//   dataForm.value.countries.push({
//     name: "",
//     code: "",
//     key: "",
//   });
// };

const handleAddProduct = () => {
  dataForm.value.products.push({
    value: "",
    key: productSelectOptions.value[0],
  });
};

const isPlainObject = (obj) => {
  return obj !== null && typeof obj === "object" && obj.constructor === Object;
};

const objToArr = (obj) => {
  if (!obj) return [];
  if (!isPlainObject(obj)) return [];
  const arr = [];
  Object.keys(obj).forEach((key) => {
    const item = typeof obj[key] === "object" ? { ...obj[key] } : { value: obj[key] };
    arr.push({
      ...item,
      key: key,
    });
  });

  return arr;
};

const arrToObj = (arr) => {
  const obj = {};
  arr.forEach((item) => {
    const { key, ...rest } = item;
    obj[item.key] = Object.keys(rest).length > 1 ? rest : item.value;
  });

  return obj;
};

const handleChange = (file) => {
  const reader = new FileReader();

  reader.onload = (e) => {
    try {
      const content = e.target.result;
      const jsonData = JSON.parse(content);
      dataForm.value.countries = objToArr(jsonData);
    } catch (error) {
      console.error("JSON解析失败:", error);
    }
  };

  reader.onerror = () => {
    console.error("文件读取错误");
  };

  reader.readAsText(file.raw);
};

const getData = () => {
  const countries = arrToObj(dataForm.value.countries);
  const products = arrToObj(dataForm.value.products);
  const iso =
    dataForm.value.countryType === "Auto"
      ? null
      : {
          "Alpha-2": "iso2",
          "Alpha-3": "iso3",
        }[dataForm.value.countryType];

  return {
    countries,
    products,
    iso,
    case_: ["Alpha-2", "Alpha-3"].includes(dataForm.value.countryType)
      ? dataForm.value.case
      : void undefined,
  };
};

const setData = (data) => {
  const { countries, products, iso } = data;
  dataForm.value.countryType = !iso
    ? "Auto"
    : {
        iso2: "Alpha-2",
        iso3: "Alpha-3",
      }[iso];
  countries && (dataForm.value.countries = objToArr(countries));
  products && (dataForm.value.products = objToArr(products));
  dataForm.value.case = data.case;
};

const handleClickDropdown = (command, e) => {
  const type = e.attrs.name;
  const list = type === "Alpha-2" ? countriesList : countriesList3;

  const countries = {};
  list.forEach((item) => {
    countries[item.code] = {
      name: item.name,
      code: item.code,
    };
  });
  const blob = new Blob([JSON.stringify(countries, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = type === "Alpha-2" ? "Alpha-2.json" : "Alpha-3.json";
  a.click();
  URL.revokeObjectURL(url);
};

defineExpose({
  getData,
  setData,
});
</script>
<style scoped>
.el-dropdown-link {
  display: flex;
  align-items: center;
  width: 130px;
  color: #409eff;
  cursor: pointer;
}
</style>
